/*
 * @Author: 鱿鱼溪学院
 * @Date: 2025-04-05 22:22:21
 * @LastEditTime: 2025-04-23 01:38:58
 * @LastEditors: 鱿鱼溪学院
 * @Description:
 * @FilePath: \yyx_ser_ts\app\middleware\AdminMiddleware.ts
 * Copyright 鱿鱼溪学院 by edu v1.0
 * 天道酬勤
 */
import { Context, Next } from 'koa'
import response from '../../utils/response'
import AdminService from '../service/AdminService'
import {
  PasswordValidationException,
  UserValidationException
} from '../exception/HttpException'
import bcrypt from 'bcryptjs'

//合法性检查,如果用户名或密码为空，返回错误
export const adminValidator = async (ctx: Context, next: Next) => {
  const { username, password } = ctx.request.body

  if (!username || !password) {
    throw new UserValidationException()
    // response.error(ctx, '用户名或密码为空!')
    // return
  }

  await next()
}

//注册时合理性检查，
export const verifyAdmin = async (ctx: Context, next: Next) => {
  //1.获取数据
  const { username } = ctx.request.body
  console.log('verify')

  try {
    const result = await AdminService.getAdminInfo({ username })

    //合理性
    if (result) {
      return response.failResponse(ctx, '用户名已存在！', [], 409)
      // throw new UserValidationException('', '用户名已存在！', 20001, 409)
    }
  } catch (err) {
    // console.error('获取用户信息失败', err) //写入日志

    throw new UserValidationException(err, '获取用户信息失败!')
    //不要忘记写return
    // return
  }

  await next()
}

//密码加密处理
export const crpytPassword = async (ctx: Context, next: Next) => {
  const { password } = ctx.request.body

  if (!password) {
    throw new PasswordValidationException('', '密码不能为空！')
  }

  //加盐
  const salt = bcrypt.genSaltSync(10)
  //hash保存的是密文
  const hash = bcrypt.hashSync(password, salt)
  ctx.request.body.password = hash

  console.log(hash, '加密后的password')

  await next()
}

//登录验证
export const verifyLogin = async (ctx: Context, next: Next) => {
  console.log('verifyLogin')
  //1.判断用户是否存在
  const { username, password } = ctx.request.body
  response.success(ctx, { username, password }) //返回用户名，用于前端显示
  try {
    const res = await AdminService.getAdminInfo({ username })

    if (!res) {
      return response.failResponse(ctx, '用户不存在！', username)
    }

    console.log(
      res.password,
      password,
      bcrypt.compareSync(password, res.password)
    )
    // return
    //2.密码是否匹配(不匹配，报错)
    if (!bcrypt.compareSync(password, res.password)) {
      return response.failResponse(ctx, '密码不匹配！', username)
    }
  } catch (err) {
    console.error(err) //写入日志
    throw new UserValidationException(err, '用户登录失败！', 20003)
  }

  await next()
}
